{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<small>\n",
    "Copyright (c) 2017 Andrew Glassner\n",
    "\n",
    "Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n",
    "\n",
    "The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n",
    "\n",
    "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n",
    "</small>\n",
    "\n",
    "\n",
    "\n",
    "# Deep Learning From Basics to Practice\n",
    "## by Andrew Glassner, https://dlbasics.com, http://glassner.com\n",
    "------\n",
    "## Chapter 12: Data Preparation\n",
    "### Notebook 3: Processing Image Features\n",
    "\n",
    "This notebook is provided as a “behind-the-scenes” look at code used to make some of the figures in this chapter. It is still in the hacked-together form used to develop the figures, and is only lightly commented."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import matplotlib.patches as patches\n",
    "import numpy as np\n",
    "import math\n",
    "\n",
    "import seaborn as sns ; sns.set()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/h5py/__init__.py:34: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n",
      "  from ._conv import register_converters as _register_converters\n",
      "Using TensorFlow backend.\n"
     ]
    }
   ],
   "source": [
    "# Make a File_Helper for saving and loading files.\n",
    "\n",
    "save_files = True\n",
    "\n",
    "import os, sys, inspect\n",
    "current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n",
    "sys.path.insert(0, os.path.dirname(current_dir)) # path to parent dir\n",
    "from DLBasics_Utilities import File_Helper\n",
    "file_helper = File_Helper(save_files)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "images = np.array([\n",
    "    [0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1 ], # the letter A\n",
    "    [1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0 ], # the letter B\n",
    "    [0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0 ], # the letter G\n",
    "    [1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1 ], # the letter M\n",
    "    [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0 ]  # the letter S\n",
    "    ])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "Simages = np.copy(images)\n",
    "for f in range(Simages.shape[1]): # for each feature\n",
    "    feature_center = np.mean(Simages[:, f])\n",
    "    feature_sigma = np.sqrt(np.var(Simages[:, f]))\n",
    "    if feature_sigma != 0:\n",
    "        Simages[:,f] = [(v-feature_center)/feature_sigma for v in Simages[:, f]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAxoAAAGXCAYAAAA08SZ9AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAAPYQAAD2EBqD+naQAAE9xJREFUeJzt3b+LnNX+B/DPzqbYuAGLLZQUwcASMrdQs3+B3S3Ef8Te\nckELudinsZGLbGe/F0GwMJ2V1cT4YyRqFCVgIAyzxc7zLWK432Zvntl85pzVz+vVpHngfc5zznk2\nb5iZZ2sYhiEAAAASTXoPAAAA+PtRNAAAgHSKBgAAkE7RAAAA0ikaAABAOkUDAABIp2gAAADpFA0A\nACDdpbEX7u7uxmKx2ORYzrS9vR2np6d9siOiT3LE9mQSp6tVn+ye99x6t88O826e7Xy3z46O6y1b\ndoVsz7X22dFvvce883t00VgsFnF0dBTT6fS5BrWu4+PjODw87JsdEW2TI44j4nC1qnvPrXe7bPOu\nOe+q2dFpvSNky/77Z3uu9cmO9us9G3nd6KIRETGdTuPg4OAcwzm/2WzWPzsi2ib/dwHL3nPr3S7b\nvGvOu2p2dFxv2bIrZFd9thR7ro3lOxoAAEA6RQMAAEinaAAAAOkUDQAAIJ2iAQAApFM0AACAdIoG\nAACQTtEAAADSKRoAAEA6RQMAAEinaAAAAOkUDQAAIJ2iAQAApFM0AACAdIoGAACQTtEAAADSKRoA\nAEA6RQMAAEinaAAAAOkUDQAAIJ2iAQAApFM0AACAdIoGAACQTtEAAADSKRoAAEA6RQMAAEh3aZ2L\nZ7PZpsZxpvl83j+7eXLE/M9/y95z690u27zbZ//5b9kzVnW9ZcuukF312VLsuTaLiIMR120NwzBs\nejAAAEAtPjoFAACkUzQAAIB0igYAAJBO0QAAANIpGgAAQLr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T8z3/LZlvv9tk973nV7ObJF2S9mydfkDNWNbvq\n+a56xqrOu2p2h/WezWZxcHDwzOu2hmEYGowHAAAoxEenAACAdIoGAACQTtEAAADSKRoAAEA6RQMA\nAEg3+udtd3d2YnFyssmxnGl7MonT1apP9vZ2nJ6e1suOiD7JhbN77vMoes97Zldd76rz7pntb2j7\n7LDXmmfba82N+eHa0UVjcXISRxExfZ4RncNxRByuVnF0dBTTadv04+PjODw8rJsdndY7omZ2730e\nBe95z+yq61113lF4r1XNDnutWfZFWO9ie23smzvWemHfNCKe/WqOXE8nMp1OR70YJDX7zxeglM2O\njutdNdt618quut5V590zu+rfMXutfXbV9S6218byHQ0AACCdogEAAKRTNAAAgHSKBgAAkE7RAAAA\n0ikaAABAOkUDAABIp2gAAADpFA0AACCdogEAAKRTNAAAgHSKBgAAkE7RAAAA0ikaAABAOkUDAABI\np2gAAADpFA0AACCdogEAAKRTNAAAgHSKBgAAkE7RAAAA0ikaAABAOkUDAABIp2gAAADpFA0AACCd\nogEAAKS7tM7Fs02N4n+YP82etU+fz+e1s5sn/7/1rpptvWtlV13vqvPumV3175i91j676noX22uz\niDgYcd3WMAzDpgcDAADU4qNTAABAOkUDAABIp2gAAADpFA0AACCdogEAAKQb/fO2u7u7sVgsNjmW\nM21HxGmXZNnlsieTOF2t+mRvb8fpaZ+Zy+6QHUXPWM9s51t2q+woesZkt8/u+Fwb88O1o4vGYrGI\no6OjmE6nzzWodR0fH8fh4WEcRUTb5IjjiDiMkF0pe7Xqu89l18qOgmesZ7bzLbtldhQ8Y7LbZ3d6\nro19b8haL+ybTqdxcDDm9Rx5nk5kGuNeDJKa/ee/sotl99znsmtlR9Ez1jO76l6T3T47ip4x2e2z\nO+zzsXxHAwAASKdoAAAA6RQNAAAgnaIBAACkUzQAAIB0igYAAJBO0QAAANIpGgAAQDpFAwAASKdo\nAAAA6RQNAAAgnaIBAACkUzQAAIB0igYAAJBO0QAAANIpGgAAQDpFAwAASKdoAAAA6RQNAAAgnaIB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vvvw0Pvn4vbJ7\nrWf2v/59FNen06bZd/5zHLffPSx7xqqe7557rep6+xvazkW457LbGfuulrVe2Le3dyNefum1cw3o\nvJ5ORHb77Cs7+/HiC682zX68/CYi+s776rWbcX3/VtPsBz9+HRF191rP7OvTafzj1kHT7PndJy8B\nrXrGqp7vnnut6nr7G9rORbjnsi8e39EAAADSKRoAAEA6RQMAAEinaAAAAOkUDQAAIJ2iAQAApFM0\nAACAdIoGAACQTtEAAADSKRoAAEA6RQMAAEinaAAAAOkUDQAAIJ2iAQAApFM0AACAdIoGAACQTtEA\nAADSKRoAAEA6RQMAAEinaAAAAOkUDQAAIJ2iAQAApFM0AACAdIoGAACQTtEAAADSKRoAAEC6S+tc\n/PDhvU2N40x/PLovu1P24+W3zbMXJz9FRN95P7h/t3n277/+EBF191rP7Pls1jz75/k8Iuqesarn\nu+deq7re/oa2cxHuuex2nmS+8czrtoZhGDY+GgAAoBQfnQIAANIpGgAAQDpFAwAASKdoAAAA6RQN\nAAAgnaIBAACkUzQAAIB0igYAAJBO0QAAANL9H/4IpXza8LHoAAAAAElFTkSuQmCC\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x11d29d4e0>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "def lerp(a, lo, hi):\n",
    "    return lo + (a * (hi-lo))\n",
    "def lerprgb(a, rgb0, rgb1):\n",
    "    return [lerp(a, rgb0[i], rgb1[i])/255 for i in [0,1,2]]\n",
    "\n",
    "plt.figure(figsize=(10,5))\n",
    "num_rows = 1 + (2*len(images))\n",
    "rect_size = 1.0/images.shape[1]\n",
    "# top rows are original letters\n",
    "for i in range(len(images)):\n",
    "    plt.subplot(num_rows, 1, i+1)\n",
    "    ax = plt.gca()\n",
    "    for f in range(images.shape[1]):\n",
    "        # Rectangle((left, top), width, height) with (0,0) in LL\n",
    "        if images[i][f] > 0:\n",
    "            fclr = [1, 0, 0]\n",
    "        else:\n",
    "            fclr = [1, 1, 1]\n",
    "        rect = patches.Rectangle((rect_size*f, 0),rect_size, rect_size,linewidth=1,edgecolor='black',facecolor=fclr)\n",
    "        ax.add_patch(rect)\n",
    "    plt.xlim(0, 1)\n",
    "    plt.ylim(0, rect_size)\n",
    "    plt.xticks([],[])\n",
    "    plt.yticks([],[])\n",
    "\n",
    "# lowers rows are standardized letters\n",
    "Smin, Smax = np.min(Simages), np.max(Simages)\n",
    "for i in range(len(images)):\n",
    "    plt.subplot(num_rows, 1, i+len(images)+2)\n",
    "    ax = plt.gca()\n",
    "    for f in range(images.shape[1]):\n",
    "        # Rectangle((left, top), width, height) with (0,0) in LL\n",
    "        sval = (Simages[i][f]-Smin)/(Smax-Smin)\n",
    "        #fclr = [sval, sval, sval]\n",
    "        fclr = lerprgb(sval, [210, 250, 255], [75, 50, 230])\n",
    "        rect = patches.Rectangle((rect_size*f, 0),rect_size, rect_size,linewidth=1,edgecolor='black',facecolor=fclr)\n",
    "        ax.add_patch(rect)\n",
    "    plt.xlim(0, 1)\n",
    "    plt.ylim(0, rect_size)\n",
    "    plt.xticks([],[])\n",
    "    plt.yticks([],[])\n",
    "file_helper.save_figure('list-processing')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
